package com.supreme.cacheserver.controller;

import com.supreme.commonboot.utils.AjaxResp;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@RestController
@RequestMapping(value = "redis-bitmap")
public class RedisBitmapController {

    @Resource
    private RedisTemplate<String, Serializable> redisTemplate;

    @Resource
    private List<RedisTemplate<String, Serializable>> redisTemplateList;

    @GetMapping(value = "setBit/{key}/{offset}/{value}")
    public AjaxResp setBit(@PathVariable(value = "key") String key,
                           @PathVariable(value = "offset") long offset,
                           @PathVariable(value = "value") boolean value) {
        Boolean result = this.redisTemplate.opsForValue().setBit(key, offset, value);
        return new AjaxResp(result);
    }

    @GetMapping(value = "getBit/{key}/{offset}")
    public AjaxResp getBit(@PathVariable(value = "key") String key,
                           @PathVariable(value = "offset") long offset) {
        Boolean result = this.redisTemplate.opsForValue().getBit(key, offset);
        return new AjaxResp(result).raw();
    }

    @GetMapping(value = "get/{key}")
    public AjaxResp get(@PathVariable(value = "key") String key) {
        Object serializable = this.redisTemplate.opsForValue().get(key);
        return new AjaxResp(serializable);
    }

    @GetMapping(value = "bitCount/{key}")
    public AjaxResp bitCount(@PathVariable(value = "key") String key) {
        Long bitCount = this.redisTemplate.execute((RedisCallback<Long>) redisConnection -> redisConnection.bitCount(key.getBytes()));
        return new AjaxResp(bitCount).raw();
    }
}
